#!/bin/env python

import sys

def phelp():
    print '''
add_mobile.py: manage mobile numbers.
Format:
    add_mobile.py [file_name]
'''

def read_file(file_name):
    with open(file_name, 'r') as fd:
        nlist = fd.readlines()
    return nlist

def write_file(file_name, nlist):
    with open(file_name, 'w') as fd:
        if nlist:
            fd.write(''.join(nlist))

def add_number(nlist, number):
    if number and number not in nlist:
        nlist.append(number)
        print number[0:11] + ' added'
    else:
        print "number exist"

def main():
    if len(sys.argv) not in [1, 2]:
        phelp()
    if len(sys.argv) == 2:
        file_name = sys.argv[1]
    else:
        file_name = "../media/ads/mobiles.txt"
    nlist = read_file(file_name)
    while True:
        num = raw_input("Please input mobile number('q' to quit):")
        if num == 'q':
            nlist.append("-----------\n")
            break
        elif len(num) == 11:
            add_number(nlist, num + '\n')
        else:
            print "input error, try again!"
    write_file(file_name, nlist)

if __name__ == '__main__':
    main()
